package com.wanmait.baohan.controller.loginController;

import com.wanmait.baohan.pojo.Staff;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * TODO
 *
 * @author hxn
 * @version 1.0
 * @date 2020/12/6 21:46
 * @description:
 */
@Controller
public class LoginController {

    /**
     * 进入登陆页面
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public void login(){}

    /**
     * shiro验证用户登录
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public String checkLogin(@RequestParam("jobNumber") String username, String password, HttpServletRequest request){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        String res = "0";
        try {
            subject.login(token);
            Staff staff = SecurityUtils.getSubject().getPrincipals().oneByType(Staff.class);
            request.getSession().setAttribute("user",staff);
        } catch (UnknownAccountException e) {
            res = "UnknownAccount";
        } catch (IncorrectCredentialsException e){
            res = "IncorrectCredentials";
        } catch (AuthenticationException e) {
            res = "error";
        }
        finally{
            return res;
        }
    }

    /**
     * hxn
     * @param request
     * @return
     * 退出登录，删除session
     */
    @RequestMapping("logout")
    public String logout(HttpServletRequest request){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        request.getSession().removeAttribute("user");
        return "/login";
    }

    /**
     * hxn
     * @param request
     * @return
     * ajax获取当前用户
     */
    @RequestMapping("getUser")
    @ResponseBody
    public Staff getUser(HttpServletRequest request){
        return (Staff)request.getSession().getAttribute("user");
    }

}
